package JDBC;

import javax.management.Query;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Xiang on 2014/8/9.
 */
public class MysqlJdbc {
    public static Connection connection;
    public static Statement statement;

    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "", "");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return conn;
    }

    public static void Insert() {
        connection = getConnection();
        try {
            String sql = "INSERT INTO T1 VALUES (4,'TEST')";
            statement = (Statement)connection.createStatement();
            int count = statement.executeUpdate(sql);
            System.out.println("插入"+count+"条数据成功!");
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void query() {
        connection = getConnection();
        try {
            String sql = "SELECT * FROM T1";
            statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);

            List<T1> t1List = new ArrayList<T1>();
            while (resultSet.next()) {
                System.out.println(resultSet.getInt("ID") + "  " + resultSet.getString("NAME"));
                T1 t1 = new T1();
                t1.setId(resultSet.getInt("ID"));
                t1.setName(resultSet.getString("NAME"));
                t1List.add(t1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        query();
    }
}
